//
//  WNUserAccountViewModel.swift
//  XLWeibo
//
//  Created by 风不会停息 on 2017/7/25.
//  Copyright © 2017年 风不会停息. All rights reserved.
//

import UIKit

class WNUserAccountViewModel: NSObject {
    
    //单例
    static let sharedViewModel : WNUserAccountViewModel = WNUserAccountViewModel()
    //引用模型
    var userAccount : WNUserAccount?
    //构造函数私有化
    private override init() {
        super.init()
        
        //读取沙盒用户模型对象
        userAccount = WNUserAccount.loadUserAccount()
        
    }
    
    //登录标记
    var isLogin : Bool{
        return accessToken != nil
    }
    
    //  获取token
    var accessToken: String? {
        guard let token = userAccount?.access_token else {
            return nil
        }
        //  字符串比较，主要判断app的版本
        //        let result = "1.0".compare("1.1")
        //  代码执行到此，token一定有值，判断token是否过期
        let result = userAccount?.expiresDate?.compare(Date())
        if result ==  ComparisonResult.orderedDescending {
            //  表示没有过期
            return token
        }
        return nil
    }
    
    //获取令牌方法
    func requestAccessToken (code : String,callBack : @escaping (Bool)->()){
        
        HMNetworkTools.sharedTools.requestAccessToken(code: code) { (response, error) in
            
            if error != nil
            {
                print(error!)
                callBack(false)

                return
            }
            
            let dic = response
            let userAccount = WNUserAccount(dic: dic as! [String : Any])
            
            self.requestUserInfo(userAccount: userAccount,callBack : callBack)
        }
    }
    
    //获取用户数据方法
    func requestUserInfo(userAccount : WNUserAccount , callBack : @escaping (Bool)->()){
        
        let token = userAccount.access_token
        
        let uid = userAccount.uid
        
        HMNetworkTools.sharedTools.requestUserinfo(access_token: token!, uid: uid) { (response, error) in
            
            if error != nil{
                
                print(error!)
                callBack(false)
                
                return
            }
            
            let dic = response as! [String : Any]
            
            userAccount.name = dic["name"] as? String
            
            userAccount.avatar_large = dic["avatar_large"] as? String
        
            userAccount.saveUserAccount()
            
            self.userAccount = userAccount
            
            callBack(true)
            
        }
    }


}
